﻿using Common.Communal;
using ERP.Domain.Workorders.Inventory;
using MediatR;
using Product.API.Read.Applications.Commands.WorkOrder.Inventory;
using Product.API.Read.DTOS;
using SqlSugar;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Product.API.Read.Applications.CommandHandlers.WorkOrder.Inventory
{
    /// <summary>
    /// 仓库分布信息显示处理
    /// </summary>
    public class WarehouseDistributionShowCommandHandler : IRequestHandler<WarehouseDistributionShowCommand, ApiResult<WarehouseDistributionDTO>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public WarehouseDistributionShowCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        public Task<ApiResult<WarehouseDistributionDTO>> Handle(WarehouseDistributionShowCommand request, CancellationToken cancellationToken)
        {
            ApiResult<WarehouseDistributionDTO> result = new ApiResult<WarehouseDistributionDTO>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            //定义开始时间
            var begin = request.StartTime;
            //定义结束时间
            var end = request.EndTime;

            var data = db.Queryable<Warehouse>()
            .InnerJoin<InventoryTransactionWordOrder>((a, b) => a.WarehouseName == b.WarehouseName)
            .Select((a, b) => new WarhouseDTO
            {
                WarehouseName = a.WarehouseName,
                WarehousrNum = a.WarehouseCapacity,
                WarehousePrice = a.InventoryAmount,
                TransactionTime = b.TransactionTime

            }).ToList();

            var data1 = data.GroupBy(o => new { o.WarehouseName, o.WarehousrNum }).Select(o => new NewWareDTO()
            {
                type = o.Key.WarehouseName,
                data = o.Key.WarehousrNum,

            }).ToList();


            result.Data = new WarehouseDistributionDTO
            {
                newWareDTOs = data1,
                wareHouse = data
            };

            return Task.FromResult(result);

        }
    }
}
